import axios from 'axios'
import {
  MessageBox,
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'
import Cookies from 'js-cookie'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    console.log(1111111, config)
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['admin-token'] = getToken()
      var venue = localStorage.getItem('venue')
      if (venue) {
        venue = JSON.parse(venue)
        console.log('看看', venue)
        config.headers['brand-id'] = venue.id
      }
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
	 * If you want to get http information such as headers or status
	 * Please return  response => response
	 */

  /**
	 * Determine the request status by custom code
	 * Here is just an example
	 * You can also judge the status by HTTP Status Code
	 */
  response => {
    const res = response.data
    console.log(1111, res)
    if (Object.prototype.toString.call(res) === '[object Blob]') { // 判断对象是否为`[对象 Blob]`
      if (!res.type.includes('application/json')) { // `application/json` 特殊类型 (可能因为错误造成的)
        const { headers, data } = response
        return { headers, data } // 返回数据 (* 注意按需组合返回指定数据 *)
      }
    }
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 0) {
      if (res.msg !== '登录成功' && res.msg !== '用户名或密码错误') {
        Message({
          message: res.msg || 'Error111',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(new Error(res.msg || 'Error222'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
